package com.job.meeting.controller;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.job.meeting.service.*;
import com.job.meeting.pojo.*;
import com.job.meeting.tools.wechatSystem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/booking")
public class bookingController {
    @Autowired
    userService us;
    @Autowired
    bookingService bs;
    @Autowired
    meetingRoomService mrs;

    wechatSystem system = null;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private class checkBean{
        String id;
        bookingTime time;
    }
    //todo: booking页面跳转
    @RequestMapping("/page")//TODO:暂未测试
    public String page()
    {
        return "booking_state1";
    }

    //初始化，根据openid找用户
    //初始化，根据openid找用户
    @ResponseBody
    @GetMapping("/greeting")
    public user init(@RequestParam("openid") String openid) {
        system = new wechatSystem(us);
        return us.getUserByOpenid(openid);
    }

    //将前端的相关信息组装起来的Json字段作为输入，
    //并提交给管理员以供审核，同时发送微信消息给所有的管理员
    @ResponseBody
    @PostMapping("/submitBooking")
    public boolean submitBooking(@RequestBody String json) {
        //todo: 正式上线后删除
        system = new wechatSystem(us);

        booking b = new booking(json);
        meetingRoom room = mrs.getMeetingRoom(b.getMeeting_room_id());

        user u = us.getUserByUserId(b.getUser_id());
        u.setReal_name(b.getReal_name());
        us.updateUser(u);

        boolean result = bs.insertBooking(b) != 0;

        wechatMessageNewMeeting meeting = new wechatMessageNewMeeting();

        bookingTime time = new Gson().fromJson(b.getTime_occupied(), bookingTime.class);
        meeting.setDate(new unit(time.getDate()));
        meeting.setTime(new unit(time.getTime()));
        meeting.setReal_name(new unit(b.getReal_name()));
        meeting.setExtra(new unit(b.getComment()));
        meeting.setMeetingRoom(new unit(room.getLocation() + " 的 " + room.getName()));
        system.sendMessage(meeting, wechatSystem.Privilege.ADMINISTRATION);

        return result;
    }

    //给定一个带有hint功能的会议室json字段，返回该会议室所有的占用情况。
    @ResponseBody
    @GetMapping("/getAllMeetingOccupancyByMeetingRoomID")
    public List<booking> getAllMeetingOccupancyByMeetingRoomID(@RequestParam("meetingRoomID") int id) {
        List<booking> bookings = bs.getAllBookingByMeetingRoomID(id);
        Collections.sort(bookings);
        return bookings;
    }

    //获得全部的位置
    @ResponseBody
    @RequestMapping("/getAllLocation")
    public List<location> getAllLocation() {
        List<location> temp = mrs.getAllLocation();
        Collections.sort(temp);
        return temp;
    }

    //根据位置获得全部的会议室信息
    @ResponseBody
    @GetMapping("/getAllMeetingRoomByLocation")
    public List<meetingRoom> getAllMeetingRoomByLocation(@RequestParam("location") String location) {
        List<meetingRoom> meetingRooms = mrs.getAllMeetingRoomByLocation(location);
        Collections.sort(meetingRooms);
        return meetingRooms;
    }

    @ResponseBody
    @GetMapping("/getAllBookingByMeetingRoomID")
    //根据会议室id获得全部的已预约
    public List<booking> getAllBookingByMeetingRoomID(@RequestParam("id") String id) {
        List<booking> bookings = bs.getAllBookingByMeetingRoomID(Integer.parseInt(id));
        Collections.sort(bookings);
        return bookings;
    }

    //根据会议室ID以及传来的占用时间json字段，
    //判断是否存在冲突。如果存在冲突，那么返回0，否则返回1
    //根据给定的会议室id以及占用时间判断是否产生冲突。
    //算法思想如下：我们假定预约成功，那么按照开始时间，将时段进行字典序从小到大的排序。
    //我们依次检查当前时段的结束时间以及下一个时段的开始时间是否合序。
    //如果不合序，那么判断产生冲突。
    @ResponseBody
    @PostMapping("/checkOccupancy")
    public boolean checkOccupancy(@RequestBody String jsonOccupancy) {
        checkBean bean = new Gson().fromJson(jsonOccupancy, checkBean.class);

        boolean result = true;
        List<booking> bookings = bs.getAllBookingByMeetingRoomID(Integer.parseInt(bean.getId()));
        List<bookingTime> bookingTimes = new ArrayList<>();
        for(booking b: bookings) {
            bookingTimes.add(new Gson().fromJson(b.getTime_occupied(), bookingTime.class));
        }
        bookingTimes.add(bean.getTime());
        Collections.sort(bookingTimes);

        for(int i = 1; i < bookingTimes.size(); i++)
        {
            bookingTime time1 = bookingTimes.get(i - 1);
            bookingTime time2 = bookingTimes.get(i);
            if(time1.getDate().equals(time2.getDate()) && Integer.parseInt(time1.getEndTime().split(": ")[0]) >
                    Integer.parseInt(time2.getBeginTime().split(": ")[0]))
            {
                result = false;
                break;
            }
        }

        return result;
    }

    //跳转去booking
    @GetMapping("/toBooking")
    public String toBooking(@RequestParam("openid") String openid) {
        return "redirect:/booking/page?openid=" + openid;
    }

    //跳转去management
    @GetMapping("/toManagement")
    public String toManagement(@RequestParam("openid") String openid) {
        return "redirect:/management/page?openid=" + openid;
    }

    //跳转去meetingRoom
    @GetMapping("/toMeetingRoom")
    public String toMeetingRoom(@RequestParam("openid") String openid) {
        return "redirect:/meetingRoom/page?openid=" + openid;
    }
}
